/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.allscore.batch.test.xxljob;

import com.allscore.batch.test.util.DateUtils;
import com.xxl.job.core.executor.XxlJobExecutor;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 *
 * @author Administrator
 */
@Configuration
public class ProductExecutorConfig {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${xxl.job.admin.addresses}")
    private String addresses;

    @Value("${xxl.job.executor.appname}")
    private String appname;

    @Value("${xxl.job.executor.port}")
    private int port;

    @Value("${xxl.job.accessToken}")
    private String accessToken;

    @Bean(initMethod = "start", destroyMethod = "destroy")
    public XxlJobExecutor xxlJobExecutor() {
        logger.info(">>>>>>>>>>> xxl-job config init.");
        XxlJobExecutor xxlJobExecutor = new XxlJobExecutor();
        String localIP = null;
        try {
            InetAddress addr = InetAddress.getLocalHost();
            localIP = addr.getHostAddress();
        } catch (UnknownHostException e) {
            logger.error("初始化xxl-job执行器，获取本机地址或IP异常：", e);
        }
        if (!DateUtils.isIPv4(localIP) && !DateUtils.isIPv6(localIP)) {
            logger.error("初始化xxl-job执行器异常，无法获取本机IP");
        }
        if ("localhost".equals(localIP) || "127.0.0.1".equals(localIP) || "::1".equals(localIP)) {
            logger.error("初始化xxl-job执行器错误，获取本机IP为：" + localIP + "，请检查本机hosts");
        }
        xxlJobExecutor.setIp(localIP);
        xxlJobExecutor.setPort(port);
        xxlJobExecutor.setAppName(appname);
        xxlJobExecutor.setAdminAddresses(addresses);
        xxlJobExecutor.setAccessToken(accessToken);
        return xxlJobExecutor;
    }
}
